import csv

def get_user_input(prompt, cast_to_type):
    while True:
        user_input = input(prompt).strip()
        if not user_input:
            print("输入的信息过少！")
            continue
        try:
            return cast_to_type(user_input)
        except ValueError:
            print(f"输入错误，请确保您输入的是{cast_to_type.__name__}类型的数据。")

def calculate_bmr(weight, height, age, gender):
    try:
        if gender.lower() == 'male':
            return (10 * weight) + (6.25 * height) - (5 * age) + 5
        else:
            return (10 * weight) + (6.25 * height) - (5 * age) - 161
    except Exception as e:
        print("数据异常，请检查输入数据是否正确。")
        return None

def save_to_csv(results, filename='bmr_calculations.csv'):
    try:
        with open(filename, mode='w', newline='', encoding='utf-8') as csvfile:
            fieldnames = ['性别', '体重', '身高', '年龄', '基础代谢率 (大卡)']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()
            for result in results:
                writer.writerow(result)
        print(f"结果已成功保存到 {filename}")
    except Exception as e:
        print(f"保存CSV文件时发生错误: {e}")

def main():
    results = []  # 创建一个空列表来存储所有结果
    while True:
        gender = get_user_input("请输入性别 (男/女): ", str)
        if gender not in ['男', '女']:
            print("请输入正确性别！")
            continue

        weight = get_user_input("请输入体重 (kg): ", float)
        height = get_user_input("请输入身高 (cm): ", float)
        age = get_user_input("请输入年龄: ", float)

        if not age.is_integer():
            print("请输入整数作为年龄！")
            continue

        if height < 100 or weight < 20:
            print("数据异常，请输入正确的身高和体重信息！")
            continue

        bmr = calculate_bmr(weight, height, int(age), 'male' if gender == '男' else 'female')
        if bmr is not None:
            results.append({
                "性别": gender,
                "体重": weight,
                "身高": height,
                "年龄": int(age),
                "基础代谢率 (大卡)": f"{bmr:.2f} kcal/day"
            })

            print(f"\n结果已保存。以下是详细信息：")
            for key, value in results[-1].items():
                print(f"{key}: {value}")

        else:
            print("无法计算BMR，请检查输入数据。")

        if input("\n是否继续添加更多结果? (y/n): ").strip().lower() == 'n':
            break

    print("\n所有保存的BMR结果：")
    for result in results:
        print(result)

    save_to_csv(results)

if __name__ == "__main__":
    main()